package com.cloud.phone.utils

import com.blankj.utilcode.util.LogUtils
import com.cloud.phone.manager.UserInfoManager
import java.io.DataOutputStream
import java.io.File
import java.io.IOException
import java.io.PrintWriter

/**
 * @auth: njb
 * @date: 2024/6/25 16:23
 * @desc: root静默安装工具类
 */
object RootUtils {
    private val TAG = "RootUtils"

    /**
     * 判断手机是否有root权限
     */
    private fun sysHasRootPermission(): Boolean {
        val printWriter: PrintWriter?
        var process: Process? = null
        try {
            process = Runtime.getRuntime().exec("su")
            printWriter = PrintWriter(process.outputStream)
            printWriter.flush()
            printWriter.close()
            val value = process.waitFor()
            return returnResult(value)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            process?.destroy()
        }
        return false
    }

    /**
     * root下执行cmd的返回值
     */
    private fun returnResult(value: Int): Boolean {
        // 代表成功
        return when (value) {
            0 -> {
                true
            }
            1 -> { // 失败
                false
            }
            else -> { // 未知情况
                false
            }
        }
    }

    /**
     * root下静默安装
     */
    private fun rootInstallApkProcess(apkPath: String): Boolean {
        val printWriter: PrintWriter?
        var process: Process? = null
        try {
            process = Runtime.getRuntime().exec("su")
            printWriter = PrintWriter(process.outputStream)
            printWriter.println("pm install -r $apkPath")
            printWriter.flush()
            printWriter.close()
            //execLinuxCommand()
            //云手机被杀死拉不起来在保活进程里面拉起
            UserInfoManager.setAppIsUpdate(true)
            val value = process.waitFor()
            return returnResult(value)
        } catch (e: Exception) {
            e.printStackTrace()
            LogUtils.e(TAG,"===安装apk出错==="+e.message)
        }finally {
            process?.destroy()
        }
        return false
    }

    /**
     * 通过Linux延时执行重启,在模拟器上面可以生效
     */
    fun execLinuxCommand() {
        val cmd = "sleep 2; am start -n com.cloud.phone/.MainActivity"
        //Runtime对象
        val runtime = Runtime.getRuntime()
        try {
            val localProcess = runtime.exec("su")
            val localOutputStream = localProcess.outputStream
            val localDataOutputStream = DataOutputStream(localOutputStream)
            localDataOutputStream.writeBytes(cmd)
            localDataOutputStream.flush()
            LogUtils.e(TAG,"准备拉起应用")
        } catch (e: IOException) {
            LogUtils.e(TAG, "拉起app失败" + e.message)
            e.printStackTrace()
        }
    }

    fun rootInstallApk(file: File) {
        LogUtils.d(TAG,"===apk文件路径为${file.path}===")
        if (!sysHasRootPermission()) {
            LogUtils.e("系统没有Root权限")
            return
        }
        LogUtils.i("系统有Root权限")
        if (!file.exists()) {
            LogUtils.e(TAG,"没有APK文件")
            return
        }
        try {
            //静默安装
            if(rootInstallApkProcess(file.path)){
                LogUtils.d(TAG,"静默安装成功")
            }else{
                LogUtils.d(TAG,"静默安装失败")
            }
        }catch (e:Exception){
            e.printStackTrace()
            LogUtils.d(TAG,"静默安装出错"+e.message)
        }
    }
}